<template>
  <div class="cards">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="凹版印刷" name="first">
        <div style="max-width: 950px; margin: 0 auto">
          <div class="ipt">￥ {{ TotalPrice }}</div>
          <el-form>
            <el-row>
              <el-col :span="8">
                <el-form-item labelWidth="100px" label="制袋袋型">
                  <el-select v-model="form.daixing" @change="handleDaixingChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in daixing"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="zhidaiPrice && userInfo.userAccount == 'admin'">
                    制袋费：￥{{ zhidaiPrice.toFixed(4) }}
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="数量">
                  <div class="fix">
                    <el-input
                      v-model="form.num"
                      @input="handleNumChange"
                      placeholder="请填写"
                    ></el-input
                    >只
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="宽度">
                  <div class="fix">
                    <el-input
                      :disabled="dwFalse"
                      @input="handleSizeChange"
                      type="Number"
                      v-model="form.dk"
                      placeholder="请填写"
                    ></el-input>
                    mm
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="高度">
                  <div class="fix">
                    <el-input
                      :disabled="dhFalse"
                      @input="handleSizeChange"
                      type="Number"
                      v-model="form.dg"
                      placeholder="请填写"
                    ></el-input>
                    mm
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="插底">
                  <el-tooltip
                    class="box-item"
                    effect="dark"
                    content="插底是展开尺寸"
                    placement="top-start"
                  >
                    <div class="fix">
                      <el-input
                        @input="handleSizeChange"
                        v-model="form.cd"
                        placeholder="请填写"
                      ></el-input>
                      mm
                    </div>
                  </el-tooltip>
                </el-form-item>
                
                <!-- 材料选择（优化为循环渲染） -->
                <template v-for="(mat, index) in materials" :key="index">
                  <el-form-item labelWidth="100px" :label="`材料${index + 1}`">
                    <div class="fix">
                      <el-select
                        style="width: 150px"
                        v-model="mat.name"
                        @change="handleMaterialSelect(index, $event)"
                      >
                        <el-option
                          :value="i.materialName"
                          :label="i.materialName"
                          v-for="(i, s) in tableData"
                          :key="s"
                        />
                      </el-select>
                      <el-input
                        @input="handleMaterialThicknessChange(index, $event)"
                        v-model="mat.thickness"
                        style="width: 50px; margin-left: 5px; margin-right: 5px"
                      ></el-input
                      >μm
                    </div>
                    <div style="color: red" v-if="mat.pricePerSquareMeter && userInfo.userAccount == 'admin'">
                      每平方米价格：￥{{ mat.pricePerSquareMeter }}
                    </div>
                  </el-form-item>
                </template>
              </el-col>
              
              <el-col :span="8">
                <el-form-item labelWidth="100px" label="印刷">
                  <el-select v-model="form.yinshua" @change="handleProcessChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in yinshua"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="yinPrice && userInfo.userAccount == 'admin'">
                    价格：￥{{ yinPrice}}
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="复合">
                  <el-select v-model="form.fuhe" @change="handleProcessChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in fuhe"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="fuhePrice && userInfo.userAccount == 'admin'">
                    价格：￥{{ fuhePrice}}
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="系数">
                  <el-select v-model="form.xishu" @change="handleFactorChange">
                    <el-option
                      :value="i.bagName"
                      :label="i.bagName"
                      v-for="(i, s) in factorData"
                      :key="s"
                    ></el-option>
                  </el-select>
                  <div v-if="xis && userInfo.userAccount == 'admin'" style="color: red">
                    系数值：{{ (xis + ke).toFixed(2) }}
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="拉链">
                  <el-select v-model="form.lalian" @change="handleAccessoryChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in lalian"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="laPrice && userInfo.userAccount == 'admin'">
                    价格：￥{{ laPrice }}
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="气阀">
                  <el-select v-model="form.qifa" @change="handleAccessoryChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in qifa"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="qiPrcie && userInfo.userAccount == 'admin'">
                    价格：￥{{ qiPrcie }}
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="吸嘴">
                  <el-select v-model="form.xizui" @change="handleAccessoryChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in qizui"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="xiPrice && userInfo.userAccount == 'admin'">
                    价格：￥{{ xiPrice }}
                  </div>
                </el-form-item>

                <el-form-item labelWidth="100px" label="特殊工艺">
                  <el-select v-model="form.tesu" @change="handleProcessChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in tesugongyi"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="tejai && userInfo.userAccount == 'admin'">价格：￥{{ tejai }}</div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="可降解">
                  <el-select v-model="form.ke" @change="handleProcessChange">
                    <el-option
                      :value="i.materialName"
                      :label="i.materialName"
                      v-for="(i, s) in tableDataJIANG"
                      :key="s"
                    />
                  </el-select>
                  <div v-if="ke && userInfo.userAccount == 'admin'" style="color: red">可降解加：{{ ke }}</div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="开机费">
                  <el-select v-model="form.kaiji" @change="handleProcessChange">
                    <el-option
                      :value="i.name"
                      :label="i.name"
                      v-for="(i, s) in kaijifei"
                      :key="s"
                    />
                  </el-select>
                  <div style="color: red" v-if="kaijiPrice && userInfo.userAccount == 'admin'">
                    价格：￥{{ kaijiPrice }}
                  </div>
                </el-form-item>
              </el-col>
              
              <el-col :span="8">
                <el-form-item labelWidth="100px" label="单只面积">
                  <div class="fix">
                    <el-input v-model="form.dm" disabled></el-input> m²
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="单面总厚度">
                  <div class="fix">
                    <el-input v-model="form.dz" disabled></el-input>mm
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="总面积">
                  <div class="fix">
                    <el-input v-model="form.mj" disabled></el-input>m²
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="单只克重">
                  <div class="fix">
                    <el-input v-model="form.dj" disabled></el-input>g
                  </div>
                </el-form-item>

                <el-form-item labelWidth="100px" label="总重量">
                  <div class="fix">
                    <el-input v-model="form.zl" disabled></el-input>kg
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="单价">
                  <div class="fix">
                    <el-input v-model="form.djia" disabled></el-input>元
                  </div>
                </el-form-item>
                <el-form-item labelWidth="100px" label="发票">
                  <el-select v-model="form.fapiao" @change="handleProcessChange">
                    <el-option
                      :value="i.value"
                      :label="i.name"
                      v-for="(i, s) in fapiao"
                      :key="s"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item labelWidth="100px" label="附加费用">
                  <div class="fix">
                    <el-input
                      @input="handleProcessChange"
                      v-model="form.fujia"
                      placeholder="请输入"
                    ></el-input
                    >元
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="btn">
            <el-button @click="CloseAdd()">清空</el-button>
            <el-button
              style="background: #7052ff; color: #fff"
              @click="calcTotalPrice()"
              >计算</el-button
            >
          </div>

          <!-- 新增计算公式回显区域 -->
          <div class="calculation-formula" v-if="calculationSteps.length > 0">
            <!-- 只有管理员可见 -->
            <el-card v-if="userInfo.userAccount == 'admin'">
              <div slot="header">
                <strong>计算公式明细</strong>
              </div>
              <ul class="formula-steps">
                <li v-for="(step, index) in calculationSteps" :key="index">
                  <span class="step-number">{{ index + 1 }}.</span>
                  <span class="step-content">{{ step.content }}</span>
                  <!-- 只显示结果值，不显示字段名 -->
                  <span class="step-result" v-if="step.result">= {{ step.result }}</span>
                </li>
              </ul>
            </el-card>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="数码印刷" name="second">
        <div style="max-width: 800px; margin: 0 auto">
          <div class="ipt">￥ {{ TotalPrice1 }}</div>
          <el-form :model="dictForm">
            <el-row>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="袋型">
                  <el-select v-model="dictForm.dict" @change="groupedDataClick">
                    <el-option
                      v-for="item in Object.keys(groupedData)"
                      :key="item"
                      :value="item"
                      :label="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="尺寸">
                  <el-select v-model="dictForm.size" @change="chase">
                    <el-option
                      v-for="item in groupedData[selectedName]"
                      :value="item.size"
                      :label="item.size"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="咖啡豆装量">
                  <el-select v-model="dictForm.houdu" @change="handleCoffeeWeightChange">
                    <el-option
                      v-for="item in groupedData[selectedName]"
                      :value="item.coffeeBeanWeight"
                      :label="item.coffeeBeanWeight"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="厚度">
                  <el-input v-model="dictForm.thickness" disabled></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="数量">
                  <el-input
                    type="Number"
                    @input="calcDigitalPrice"
                    v-model="dictForm.num"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="最低起订金额">
                  <el-input
                    type="Number"
                    v-model="dictForm.price"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item labelWidth="100px" label="单价">
                  <el-input
                    type="Number"
                    v-model="dictForm.unit"
                    disabled
                  ></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item labelWidth="100px" label="附加费用">
                  <el-input
                    @input="calcDigitalPrice"
                    type="Number"
                    v-model="dictForm.resPrice"
                    placeholder="请输入"
                  ></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="btn">
            <el-button @click="Close()">清空</el-button>
            <el-button
              style="background: #7052ff; color: #fff"
              @click="calcDigitalPrice()"
              >计算</el-button
            >
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="丝网和烫金" name="third">
        <div style="max-width: 800px; margin: 0 auto">
          <div class="ipt">￥ {{ TotalPrice2 }}</div>
          <el-form labelWidth="100px" :model="selectedValues">
            <el-row>
              <el-col :span="12">
                <el-form-item label="起订量">
                  <el-select
                    v-model="selectedValues.quantity"
                    @change="updatePrice"
                    placeholder="请选择起订量"
                  >
                    <el-option
                      v-for="item in uniqueValues.quantity"
                      :key="item"
                      :label="item.toString()"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="印刷区域">
                  <el-select
                    v-model="selectedValues.printArea"
                    @change="updatePrice"
                    placeholder="请选择印刷区域"
                  >
                    <el-option
                      v-for="item in uniqueValues.printArea"
                      :key="item"
                      :label="item.toString()"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="logo颜色">
                  <el-select
                    v-model="selectedValues.logoColor"
                    @change="updatePrice"
                    placeholder="请选择logo颜色"
                  >
                    <el-option
                      v-for="item in uniqueValues.logoColor"
                      :key="item"
                      :label="item.toString()"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="印刷面数">
                  <el-select
                    v-model="selectedValues.printSides"
                    @change="updatePrice"
                    placeholder="请选择印刷面数"
                  >
                    <el-option
                      v-for="item in uniqueValues.printSides"
                      :key="item"
                      :label="item.toString()"
                      :value="item"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="印刷单价">
                  <div class="fix">
                    <el-input disabled v-if="!matchedData"></el-input>
                    <el-input
                      disabled
                      v-else
                      v-model="matchedData.unitPrice"
                    ></el-input>
                    元
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="印刷总价">
                  <div class="fix">
                    <el-input disabled v-if="!matchedData"></el-input>
                    <el-input
                      disabled
                      v-else
                      v-model="matchedData.totalPrice"
                    ></el-input
                    >元
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="袋子单价">
                  <div class="fix">
                    <el-input
                      @input="calculateSum"
                      v-model="matc.daidan"
                      placeholder="请输入"
                    ></el-input
                    >元
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="运费">
                  <div class="fix">
                    <el-input v-model="matc.yun" placeholder="请输入" @input="calcSilkPrice"></el-input
                    >元
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="总单价">
                  <div class="fix">
                    <el-input
                      v-model="matc.zong"
                      disabled
                    ></el-input
                    >元
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="附加费用">
                  <div class="fix">
                    <el-input v-model="matc.fu" placeholder="请输入" @input="calcSilkPrice"></el-input
                    >元
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="btn">
            <el-button @click="CloseAdd(), (TotalPrice2 = 0)">清空</el-button>
            <el-button
              style="background: #7052ff; color: #fff"
              @click="calcSilkPrice()"
              >计算</el-button
            >
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import {
  defineAsyncComponent,
  onMounted,
  computed,
  ref,
  watch,
} from "vue";
import type { TabsPaneContext } from "element-plus";
import { ElMessage } from "element-plus";
const Card = defineAsyncComponent(() => import("@/components/cards/index.vue"));
import { User, Plus, Warning, QuestionFilled } from "@element-plus/icons-vue";
import {
  factorList,
  dictList,
  dict,
  list,
  bronzingList,
  productprices,
} from "@/api/index";

// 通用工具函数
const formatDecimal = (num: number, decimalPlaces: number = 6): number => {
  const factor = Math.pow(10, decimalPlaces);
  return Math.floor(num * factor) / factor;
};

interface MaterialParams {
  density: number;
  thickness: number;
  pricePerGram: number;
}
const calcMaterialData = ({ density, thickness, pricePerGram }: MaterialParams) => {
  const thicknessInCm = thickness * 0.0001;
  const areaInCm2 = 10000;
  const gramPerSquareMeter = formatDecimal(density * thicknessInCm * areaInCm2);
  const pricePerSquareMeter = formatDecimal(gramPerSquareMeter * pricePerGram);
  return { gramPerSquareMeter, pricePerSquareMeter };
};

const getPriceByQuantity = (
  quantity: number,
  prices: {
    p500: number,
    p1000: number;
    p2000: number;
    p3000: number;
    p4000: number;
    p5000: number;
    p10000: number;
  }
): number => {
  if (quantity <= 500) return prices.p500;
  if (quantity <= 1000) return prices.p1000;
  if (quantity <= 2000) return prices.p2000;
  if (quantity <= 3000) return prices.p3000;
  if (quantity <= 4000) return prices.p4000;
  if (quantity <= 5000) return prices.p5000;
  return prices.p10000;
};

// 凹版印刷相关
const activeName = ref("first");
const TotalPrice = ref(0);
const TotalPrice1 = ref(0);
const TotalPrice2 = ref(0);

const form = ref({
  xishu: "",
  fujia: 0,
  mj: 0,
  dm: 0,
  dj: 0,
  dz: 0,
  num: 1,
  dk: 0,
  dg: 0,
  cd: 0,
  djia: 0,
  lalian: "",
  xizui: "",
  qifa: "",
  fapiao: "1",
  ke: "",
  tesu: "",
  fuhe: "",
  yinshua: "",
  daixing: "",
  kaiji: "",
});

// 材料数据管理（优化为数组）
const materials = ref<Array<{
  name: string;
  thickness: number;
  density: number;
  pricePerGram: number;
  gramPerSquareMeter: number;
  pricePerSquareMeter: number;
}>>([
  { name: "", thickness: 0, density: 0, pricePerGram: 0, gramPerSquareMeter: 0, pricePerSquareMeter: 0 },
  { name: "", thickness: 0, density: 0, pricePerGram: 0, gramPerSquareMeter: 0, pricePerSquareMeter: 0 },
  { name: "", thickness: 0, density: 0, pricePerGram: 0, gramPerSquareMeter: 0, pricePerSquareMeter: 0 },
  { name: "", thickness: 0, density: 0, pricePerGram: 0, gramPerSquareMeter: 0, pricePerSquareMeter: 0 },
  { name: "", thickness: 0, density: 0, pricePerGram: 0, gramPerSquareMeter: 0, pricePerSquareMeter: 0 },
]);

// 工艺参数
const zhidaiPrice = ref(0);
const laPrice = ref(0);
const lake = ref(0);
const xiPrice = ref(0);
const xiKe = ref(0);
const fuhePrice = ref(0);
const chen = ref(0);
const kaijiPrice = ref(0);
const ke = ref(0);
const yinPrice = ref(0);
const qiPrcie = ref(0);
const qiKe = ref(0);
const tejai = ref(0);
const tePrice = ref(0);
const xis = ref(0);
const su = ref(0);
const KAINUM = ref(10000);
const daxingValue = ref("");
const dwFalse = ref(false);
const dhFalse = ref(false);

// 数据列表
const factorData = ref([]);
const tableData = ref([]);
const listData = ref([]);
const productDataList = ref([]);
const daixing = ref([]);
const lalian = ref([]);
const qifa = ref([]);
const fuhe = ref([]);
const qizui = ref([]);
const tesugongyi = ref([]);
const kaijifei = ref([]);
const yinshua = ref([]);
const tableDataJIANG = ref([]);
const fapiao = ref([]);

// 面积和制袋费计算
const calcSingleAreaAndBagFee = (
  daixing: string,
  dk: number,
  dg: number,
  cd: number
) => {
  const dkM = dk / 1000;
  const dgM = dg / 1000;
  const cdM = cd / 1000;
  let area = 0;
  let bagFee = 0;

  switch (daixing) {
    case "三边封袋":
      area = dkM * dgM * 2;
      bagFee = dkM * 0.2;
      break;
    case "三边封中封袋":
      area = (dkM + 0.015) * dgM * 2;
      bagFee = dgM * 0.2;
      break;
    case "自立袋":
      area = (dgM * 2 + cdM) * dkM;
      bagFee = dkM * 0.2;
      break;
    case "八边封":
      area = (dkM + cdM) * 2 * (0.5 * cdM + dgM);
      bagFee = dkM * 1;
      break;
    case "卷膜":
      area = dkM * dkM;
      bagFee = 0;
      break;
    case "风琴袋":
      area = (dkM + cdM + 0.015) * 2 * dgM;
      bagFee = dgM * 0.2;
      break;
    case "四边封":
      area = (dkM + cdM) * 2 * dgM;
      bagFee = dgM * 0.2;
      break;
    case "中封袋":
      area = (dkM + 0.015) * 2 * dgM;
      bagFee = dgM * 0.2;
      break;
    case "四边封+拉链":
      area = (dkM + cdM) * 2 * dgM;
      bagFee = dkM * 1;
      break;
    default:
      area = 0;
      bagFee = 0;
  }
  return {
    area: formatDecimal(area, 4),
    bagFee: formatDecimal(bagFee, 4),
  };
};

// 事件处理
const handleDaixingChange = (val: any) => {
  const index = daixing.value.findIndex((item) => item.name === val);
  daxingValue.value = daixing.value[index].value;
  
  // 自动匹配开机费
  kaijifei.value.forEach((item) => {
    if (item.name.includes(daixing.value[index].name)) {
      form.value.kaiji = item.name;
      kaijiPrice.value = item.value / Number(KAINUM.value);
    }
  });
  
  // 自动匹配系数
  factorData.value.forEach((item) => {
    if (item.bagName.includes(daixing.value[index].name)) {
      form.value.xishu = item.bagName;
      xis.value = item.areaRange1;
    }
  });
  
  handleAccessoryChange();
  handleSizeChange();
};

const handleSizeChange = () => {
  const { daixing, dk, dg, cd, num } = form.value;
  if (!daixing || !dk || !dg) return;

  // 计算面积和制袋费
  const { area, bagFee } = calcSingleAreaAndBagFee(daixing, dk, dg, cd || 0);
  form.value.dm = area;
  zhidaiPrice.value = bagFee;
  
  // 计算总面积
  form.value.mj = formatDecimal(area * num, 4);
  console.log('计算总面积',form.value.mj,'dm',area)
  // 更新厚度
  form.value.dz = formatDecimal(
    materials.value.reduce((sum, mat) => sum + mat.thickness, 0) / 1000,
    4
  );
  // 计算单只克重
  calculateSingleWeight();
  // 重新计算价格
  calcTotalPrice();
};

const handleNumChange = () => {
  const { dm, num } = form.value;
  form.value.mj = formatDecimal(dm * num, 4);
  // 重新计算总重量
  calculateSingleWeight();
  calcTotalPrice();
};

const handleMaterialSelect = (index: number, val: any) => {
  const matIndex = tableData.value.findIndex((item) => item.materialName === val);
  if (matIndex === -1) return;
  
  const material = tableData.value[matIndex];
  materials.value[index] = {
    ...materials.value[index],
    name: val,
    thickness: material.thickness,
    density: material.density,
    pricePerGram: material.pricePerGram,
  };
  
  const { gramPerSquareMeter, pricePerSquareMeter } = calcMaterialData({
    density: material.density,
    thickness: material.thickness,
    pricePerGram: material.pricePerGram,
  });
  
  materials.value[index].gramPerSquareMeter = gramPerSquareMeter;
  materials.value[index].pricePerSquareMeter = pricePerSquareMeter;
  // 更新总厚度
  form.value.dz = formatDecimal(
    materials.value.reduce((sum, mat) => sum + mat.thickness, 0) / 1000,
    4
  );

  calcTotalPrice();
};

const handleMaterialThicknessChange = (index: number, val: any) => {
  materials.value[index].thickness = Number(val);
  
  const { gramPerSquareMeter, pricePerSquareMeter } = calcMaterialData({
    density: materials.value[index].density,
    thickness: Number(val),
    pricePerGram: materials.value[index].pricePerGram,
  });
  
  materials.value[index].gramPerSquareMeter = gramPerSquareMeter;
  materials.value[index].pricePerSquareMeter = pricePerSquareMeter;
  
  // 更新总厚度
  form.value.dz = formatDecimal(
    materials.value.reduce((sum, mat) => sum + mat.thickness, 0) / 1000,
    4
  );
  // 计算单只克重
  calculateSingleWeight();
  
  calcTotalPrice();
};

const handleAccessoryChange = () => {
  const { daixing, dk } = form.value;
  
  // 拉链计算
  const laIndex = lalian.value.findIndex((item) => item.name === form.value.lalian);
  const laM = laIndex !== -1 ? Number(lalian.value[laIndex].value) : 0;
  if (form.value.lalian) {
    lake.value = form.value.lalian === "普通拉链" ? 4.957 : 10.537;
    if(form.value.lalian === '无拉链') lake.value = 0
    if (["三边封袋", "自立袋", "八边封"].includes(daixing)) {
      laPrice.value = formatDecimal((dk / 1000) * laM, 2);
      lake.value = formatDecimal(lake.value * (dk / 1000), 6);
    } else if (daixing === "四边封+拉链") {
      laPrice.value = formatDecimal(dk * 0.001, 2);
      lake.value = formatDecimal(lake.value * (dk / 1000), 6);
    } else {
      laPrice.value = 0;
    }
  } else {
    laPrice.value = 0;
    lake.value = 0;
  }
  console.log('拉链计算 ',laM,'laPrice.value',laPrice.value,'lake.value',lake.value)

  
  // 吸嘴计算
  const xiIndex = qizui.value.findIndex((item) => item.name === form.value.xizui);
  xiPrice.value = xiIndex !== -1 ? Number(qizui.value[xiIndex].value) : 0;
  
  switch (form.value.xizui) {
    case "普通8.6mm": xiKe.value = 3; break;
    case "普通10mm": xiKe.value = 3.5; break;
    case "普通13mm": xiKe.value = 6; break;
    case "普通16mm": xiKe.value = 9; break;
    case "普通22mm": xiKe.value = 11; break;
    case "普通33mm": xiKe.value = 16.5; break;
    default: xiKe.value = 0;
  }
  
  // 气阀计算
  const qiIndex = qifa.value.findIndex((item) => item.name === form.value.qifa);
  qiPrcie.value = qiIndex !== -1 ? Number(qifa.value[qiIndex].value) : 0;
  qiKe.value = form.value.qifa && form.value.qifa !== "无阀" ? 1.5 : 0;
  
  calcTotalPrice();
};




const handleProcessChange = () => {
  // 复合工艺计算（保持不变）
  const fuIndex = fuhe.value.findIndex((item) => item.name === form.value.fuhe);
  fuhePrice.value = fuIndex !== -1 ? Number(fuhe.value[fuIndex].value) : 0;
  console.log('复合工艺计算（保持不变）',fuhePrice.value)

  
  // 印刷计算 - 不乘以单只面积
  const yinIndex = yinshua.value.findIndex((item) => item.name === form.value.yinshua);
  // 直接使用印刷单价，不乘以面积
  yinPrice.value = yinIndex !== -1 ? Number(yinshua.value[yinIndex].value) : 0;
  
  // 验证宽度和高度是否已填写（仅做提示，不影响印刷价格计算）
  const dk = Number(form.value.dk);
  const dg = Number(form.value.dg);
  let hasValidDimensions = true;
  
  if (isNaN(dk) || dk <= 0) {
    ElMessage.warning("请填写有效的宽度");
    hasValidDimensions = false;
  }
  
  if (isNaN(dg) || dg <= 0) {
    ElMessage.warning("请填写有效的高度");
    hasValidDimensions = false;
  }
  
  // 特殊工艺计算（保持不变）
  const teIndex = tesugongyi.value.findIndex((item) => item.name === form.value.tesu);
  tePrice.value = teIndex !== -1 ? Number(tesugongyi.value[teIndex].value) : 0;
  
  const safeDk = hasValidDimensions ? dk : 0;
  const safeDg = hasValidDimensions ? dg : 0;
  
  if (["哑油", "磨砂哑油", "触感哑油"].includes(form.value.tesu)) {
    tejai.value = hasValidDimensions ? formatDecimal(tePrice.value * (safeDk / 1000) * (safeDg / 1000), 2) : 0;
  } else if (form.value.tesu === "开窗" && hasValidDimensions && safeDk) {
    tejai.value = formatDecimal((tePrice.value * safeDk) / 1000, 2);
  } else {
    tejai.value = tePrice.value;
  }
  
  // 可降解计算（保持不变）
  if (form.value.ke && form.value.ke !== "无") {
    const jiangIndex = tableDataJIANG.value.findIndex(
      (item) => item.materialName === form.value.ke
    );
    if (jiangIndex !== -1 && tableDataJIANG.value[jiangIndex].value) {
      ke.value = Number(tableDataJIANG.value[jiangIndex].value) || 0.05;
      jiangjieKe.value = Number(tableDataJIANG.value[jiangIndex].value) || 0.05;
    } else {
      ke.value = 0.05;
      jiangjieKe.value = 0.05
    }
  } else {
    ke.value = 0;
    jiangjieKe.value = 0;
  }
  
  // 开机费计算（保持不变）
  const kaiIndex = kaijifei.value.findIndex((item) => item.name === form.value.kaiji);
  const kainum = Number(KAINUM.value) || 1;
  kaijiPrice.value = kaiIndex !== -1 ? Number(kaijifei.value[kaiIndex].value) / kainum : 0;
  
  if (hasValidDimensions) {
    calcTotalPrice();
  }
};

// 修正印刷价格的watch监听（不乘以单只面积）
watch(
  () => [form.value.yinshua, form.value.dk, form.value.dg, form.value.dm],
  (newValues) => {
    const [newYinshua, newDk, newDg] = newValues;

    if (!newYinshua) {
      yinPrice.value = 0;
      return;
    }

    const dkNum = Number(newDk);
    const dgNum = Number(newDg);

    // 仅验证尺寸有效性，不影响印刷价格计算
    if (isNaN(dkNum) || dkNum <= 0 || isNaN(dgNum) || dgNum <= 0) {
      return;
    }

    // 直接使用印刷单价，不乘以面积
    const yinIndex = yinshua.value.findIndex(item => item.name === newYinshua);
    yinPrice.value = yinIndex !== -1 ? Number(yinshua.value[yinIndex].value) : 0;
    
    calcTotalPrice();
  },
  { immediate: true }
);


//可降解参数
const jiangjieKe = ref(0);

const handleFactorChange = (val: any) => {
  const index = factorData.value.findIndex((item) => item.bagName === val);
  if (index === -1) return;
  
  const { mj } = form.value;
  if (mj < 4000) {
    xis.value = factorData.value[index].areaRange1;
  } else if (mj < 6000) {
    xis.value = factorData.value[index].areaRange2;
  } else if (mj < 8000) {
    xis.value = factorData.value[index].areaRange3;
  } else {
    xis.value = factorData.value[index].areaRange4;
  }
  
  calcTotalPrice();
};
// 调整计算步骤类型，只定义必要的显示字段
const calculationSteps = ref<Array<{
  content: string;  // 计算步骤描述
  result?: string;  // 计算结果值（仅存储值，不包含字段名）
}>>([]);


// 新增：单只克重计算函数
const calculateSingleWeight = () => {
  const { dm, num } = form.value;
  if (!dm || !num) return;
  
  // 计算所有材料的总克重（每平方米克重 × 单只面积）
  const totalGramPerSquareMeter = materials.value.reduce(
    (sum, mat) => sum + mat.gramPerSquareMeter, 
    0
  );
  console.log('totalGramPerSquareMeter',totalGramPerSquareMeter)
  // 单只克重 = 总每平方米克重 × 单只面积
  const singleWeight = formatDecimal(totalGramPerSquareMeter * dm, 4);
  form.value.dj = formatDecimal(singleWeight + Number(xiKe.value) + Number(qiKe.value),4) +Number(lake.value);
  console.log('克重',xiKe.value+qiKe.value)
  // 总重量 = 单只克重 × 数量
  form.value.zl = formatDecimal(Number(form.value.dj) * Number(num), 4) / 1000;
  form.value.zl = formatDecimal(form.value.zl,4)
};

// 核心计算函数（保持计算逻辑，优化结果存储方式）
const calcTotalPrice = () => {
  calculationSteps.value = [];
  calculateSingleWeight();
  const { daixing, num, dk, dg, cd, fapiao, fujia } = form.value;
  if (!daixing || !dk || !dg || !num) return;

  // 1. 基础参数计算
  const { area: singleArea, bagFee } = calcSingleAreaAndBagFee(daixing, dk, dg, cd || 0);
  const totalArea = formatDecimal(singleArea * num, 4);
  const isSmallOrder = totalArea <= 4000;
  
  calculationSteps.value.push({
    content: `基础参数计算：袋型=${daixing}，宽度=${dk}mm，高度=${dg}mm，数量=${num}只`
  });
  calculationSteps.value.push({
    content: `单只面积`,
    result: `${singleArea} 平方米`
  });
  calculationSteps.value.push({
    content: `单只克重 = 材料总每平方米克重 × 单只面积 + 拉链 + 气阀 + 吸嘴`,
    result: `${formatDecimal(materials.value.reduce((sum, mat) => sum + mat.gramPerSquareMeter, 0),4)} × ${singleArea} + ${lake.value}+${qiKe.value}+${xiKe.value} = ${form.value.dj} g/m²`
  });
  calculationSteps.value.push({
    content: `总重量 = 单只克重 × 数量`,
    result: `${form.value.dj} × ${num} = ${form.value.zl / 1000} kg`
  });
  calculationSteps.value.push({
    content: `制袋费`,
    result: `${bagFee} 元`
  });

  // 2. 各项成本计算（保持计算逻辑不变）
  const materialTotalPrice = materials.value.reduce(
    (sum, mat) => sum + mat.pricePerSquareMeter,
    0
  );
  const materialCost = formatDecimal(materialTotalPrice * singleArea, 4);
  
  const printCost = formatDecimal(yinPrice.value * singleArea ,4);
  
  const compositeUnitCost = fuhePrice.value ;
  const compositeCost = formatDecimal(compositeUnitCost * singleArea, 4);
  
  const accessoryCost = formatDecimal(
    laPrice.value + qiPrcie.value + xiPrice.value,
    4
  );
  
  const specialProcessCost = tejai.value;
  const machineCost = isSmallOrder ? kaijiPrice.value : 0;
  
  calculationSteps.value.push({
    content: `材料成本 = 材料单价 × 单只面积`,
    result: `${materialTotalPrice} × ${singleArea} = ${materialCost} 元`
  });
  calculationSteps.value.push({
    content: `印刷成本= 印刷单价 x 单只面积`,
    result: `${yinPrice.value} x ${singleArea} = ${printCost}元`
  });


  calculationSteps.value.push({
    content: `复合成本 = 复合单位成本 × 单只面积`,
    result: `${fuhePrice.value} × ${singleArea} = ${compositeCost} 元`
  });
  calculationSteps.value.push({
    content: `配件成本（拉链+气阀+吸嘴）`,
    result: `${laPrice.value} + ${qiPrcie.value} + ${xiPrice.value} = ${accessoryCost} 元`
  });
  calculationSteps.value.push({
    content: `特殊工艺费用`,
    result: `${specialProcessCost} 元`
  });
  calculationSteps.value.push({
    content: `开机费（小订单）`,
    result: `${machineCost} 元`
  });

  // 3. 系数计算及后续步骤（保持不变）
  const factor = xis.value + Number(jiangjieKe.value || 0);
  
  calculationSteps.value.push({
    content: `总系数 = 基础系数 + 可降解系数`,
    result: `${xis.value} + ${jiangjieKe.value || 0} = ${formatDecimal(factor,3)}`
  });

  const costSum = formatDecimal(
    materialCost + printCost + compositeCost,
    4
  );
  calculationSteps.value.push({
    content: `材料+印刷+复合成本总和`,
    result: `${materialCost} + ${printCost} + ${compositeCost} = ${costSum} 元`
  });

  const factorCost = formatDecimal(
    costSum * factor,
    4
  );
  calculationSteps.value.push({
    content: `成本总和 × 总系数`,
    result: `${costSum} × ${factor} = ${formatDecimal(factorCost,3)} 元`
  });

  const totalBeforeTax = formatDecimal(
    factorCost + bagFee + accessoryCost + specialProcessCost + machineCost,
    4
  );
  calculationSteps.value.push({
    content: `加上其他费用 = 上述结果 + 制袋费 + 配件成本 + 特殊工艺费用 + 开机费`,
    result: `${factorCost} + ${bagFee} + ${accessoryCost} + ${specialProcessCost} + ${machineCost} = ${totalBeforeTax} 元`
  });

  const taxRate = Number(fapiao) || 1;
  // const hanshui = taxRate
  const singlePriceWithTax = formatDecimal(totalBeforeTax * taxRate, 4);
  
  calculationSteps.value.push({
    content: `最终单价 = 上述结果 × 税率(${taxRate})`,
    result: `${totalBeforeTax} × ${taxRate} = ${singlePriceWithTax} 元`
  });

  form.value.djia = singlePriceWithTax;
  TotalPrice.value = formatDecimal(
    singlePriceWithTax * num + Number(fujia || 0),
    4
  );
  
  calculationSteps.value.push({
    content: `总价 = 最终单价 × 数量 + 附加费用`,
    result: `${singlePriceWithTax} × ${num} + ${fujia || 0} = ${TotalPrice.value} 元`
  });
};
// 数码印刷相关
const dictForm = ref({
  dict: "",
  size: "",
  houdu: "",
  price: "",
  num: "",
  resPrice: 0,
  thickness: "",
  jg: 0,
  unit: 0,
});

const selectedName = ref<string>("");
const indexs = ref(0);

interface BagData {
  remarks:string;
  pricePer1000Units: number;
  pricePer2000Units: number;
  materialName: string;
  pricePer3000Units: number;
  pricePer4000Units: number;
  pricePer5000Units: number;
  pricePer10000Units: number;
  coffeeBeanWeight: string;
  thickness: string;
  size: string;
  minOrderAmount: string;
}

const groupedData = computed(() => {
  return productDataList.value.reduce((acc, item) => {
    if (!acc[item.materialName]) {
      acc[item.materialName] = [];
    }
    acc[item.materialName].push(item);
    return acc;
  }, {} as Record<string, BagData[]>);
});

// const groupedDataClick = (val: any) => {
//   selectedName.value = val;
//   if (groupedData.value[val] && groupedData.value[val].length > 0) {
//     dictForm.value.price = groupedData.value[val][0].minOrderAmount;
//     dictForm.value.thickness = groupedData.value[val][0].thickness;
//   }
//   calcDigitalPrice();
// };

const chase = (val: any) => {
  const index = groupedData.value[selectedName.value]?.findIndex((item) => item.size === val) || -1;
  if (index === -1) return;
  
  indexs.value = index;
  const item = groupedData.value[selectedName.value][index];
  
  // 根据尺寸匹配厚度
  switch (val) {
    case "110*190*80": dictForm.value.houdu = "250g"; break;
    case "85*190*60": dictForm.value.houdu = "100g"; break;
    case "100*185*60": dictForm.value.houdu = "150g"; break;
    case "100*190*75": dictForm.value.houdu = "200g"; break;
    case "120*200*70": dictForm.value.houdu = "300g"; break;
    case "127*200*80": dictForm.value.houdu = "340g"; break;
    case "110*280*80":
    case "190*200*80": dictForm.value.houdu = "500g"; break;
    case "140*210*100": dictForm.value.houdu = "900g"; break;
    case "140*345*95345*95": dictForm.value.houdu = "1kg"; break;
    case "180*415*105": dictForm.value.houdu = "2kg"; break;
    default: break;
  }
  
  calcDigitalPrice();
};

// 数码印刷相关优化
// 获取当前袋型下的所有unique装量（用于下拉选项）
const getUniqueWeights = computed(() => {
  if (!dictForm.value.dict) return [];
  const weights = groupedData.value[dictForm.value.dict]?.map(item => item.coffeeBeanWeight) || [];
  return [...new Set(weights)].filter(Boolean); // 去重并过滤空值
});

// 处理咖啡豆装量变化：自动匹配尺寸、厚度、最低起订金额
const handleCoffeeWeightChange = (val: string) => {
  if (!dictForm.value.dict || !val) return;

  // 从当前袋型的产品数据中找到匹配装量的产品
  const matchedProduct = groupedData.value[dictForm.value.dict]?.find(
    item => item.coffeeBeanWeight === val
  );
  console.log('厚度、最低起订金额',matchedProduct)
  if (!matchedProduct) {
    ElMessage.warning(`未找到装量为${val}的匹配数据`);
    return;
  }

  // 自动填充尺寸、厚度、最低起订金额
  dictForm.value.size = matchedProduct.size; // 匹配尺寸
  dictForm.value.thickness = matchedProduct.thickness; // 匹配厚度
  dictForm.value.price = matchedProduct.minOrderAmount; // 匹配最低起订金额

  // 自动触发价格计算（如果已填写数量）
  if (dictForm.value.num) {
    calcDigitalPrice();
  }
};

// 优化袋型变化时的处理：如果已有装量，自动匹配对应数据
const groupedDataClick = (val: any) => {
  selectedName.value = val;
  if (groupedData.value[val] && groupedData.value[val].length > 0) {
    // 重置装量相关字段
    dictForm.value.houdu = '';
    dictForm.value.size = '';
    dictForm.value.thickness = '';
    dictForm.value.price = '';
  }
  calcDigitalPrice();
};



const kafi = (val: any) => {
  if (!dictForm.value.dict) return;
  
  // 根据装量匹配尺寸
  if (dictForm.value.dict === "单侧拉链方底袋") {
    const sizeMap: Record<string, string> = {
      "100g": "85*190*60",
      "150g": "100*185*60",
      "200g": "100*190*75",
      "250g": "110*190*80",
      "300g": "120*200*70",
      "340g": "127*200*80",
      "500g": "110*280*80",
      "800g": "140*210*100",
      "1kg": "140*345*95",
      "2kg": "180*415*105",
    };
    dictForm.value.size = sizeMap[val] || "";
  }
  
  calcDigitalPrice();
};

const calcDigitalPrice = () => {
  const { num, resPrice, dict, size } = dictForm.value;
  if (!dict || !size || !num) return;

  const product = groupedData.value[dict]?.find(item => item.size === size);
  if (!product) return;

  // 计算单价
  const unitPrice = getPriceByQuantity(num, {
    p500: product.remarks,
    p1000: product.pricePer1000Units,
    p2000: product.pricePer2000Units,
    p3000: product.pricePer3000Units,
    p4000: product.pricePer4000Units,
    p5000: product.pricePer5000Units,
    p10000: product.pricePer10000Units,
  });

  // 计算总价
  const totalBeforeAdd = formatDecimal(unitPrice * num, 2);
  if (totalBeforeAdd < Number(product.minOrderAmount)) {
    ElMessage.warning(`最低起订金额不能低于${product.minOrderAmount}元`);
    return;
  }
  console.log('计算价格',unitPrice)
  dictForm.value.unit = unitPrice;
  TotalPrice1.value = formatDecimal(totalBeforeAdd + Number(resPrice || 0), 2);
};

// 丝网和烫金相关
interface PrintData {
  quantity: number;
  printArea: string;
  logoColor: string;
  printSides: number;
  totalPrice: number;
  unitPrice: number;
}

interface SelectedValues {
  quantity: number | null;
  printArea: string | null;
  logoColor: string | null;
  printSides: number | null;
}

const selectedValues = ref<SelectedValues>({
  quantity: null,
  printArea: null,
  logoColor: null,
  printSides: null,
});

const matc = ref({
  daidan: 0,
  yun: 0,
  zong: 0,
  fu: 0,
});

const matchedData = ref<PrintData | null>(null);

const uniqueValues = computed(() => {
  return {
    quantity: [...new Set(listData.value.map((item: any) => item.quantity))],
    printArea: [...new Set(listData.value.map((item: any) => item.printArea))],
    logoColor: [...new Set(listData.value.map((item: any) => item.logoColor))],
    printSides: [...new Set(listData.value.map((item: any) => item.printSides))],
  };
});

const updatePrice = () => {
  matc.value.zong = 0;
  matc.value.daidan = 0;
  
  if (!selectedValues.value.quantity || !selectedValues.value.printArea || 
      !selectedValues.value.logoColor || !selectedValues.value.printSides) {
    matchedData.value = null;
    return;
  }

  const matched = listData.value.find((item: any) =>
    item.quantity === selectedValues.value.quantity &&
    item.printArea === selectedValues.value.printArea &&
    item.logoColor === selectedValues.value.logoColor &&
    item.printSides === selectedValues.value.printSides
  );
  
  matchedData.value = matched || null;
};

const calculateSum = () => {
  if (matchedData.value && matc.value.daidan) {
    matc.value.zong = formatDecimal(matchedData.value.unitPrice + Number(matc.value.daidan), 2);
  }
};

const calcSilkPrice = () => {
  if (!matchedData.value || !selectedValues.value.quantity || !matc.value.zong) {
    ElMessage.error("请选择完整的选项以计算价格！");
    return;
  }

  TotalPrice2.value = formatDecimal(
    Number(matchedData.value.totalPrice) +
    (Number(matc.value.daidan) * Number(selectedValues.value.quantity)) +
    Number(matc.value.yun || 0) +
    Number(matc.value.fu || 0),
    2
  );
};

// 通用方法
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

const CloseAdd = () => {
  // 重置凹版印刷表单
  form.value = {
    xishu: "",
    fujia: 0,
    mj: 0,
    dm: 0,
    dj: 0,
    dz: 0,
    num: 1,
    dk: 0,
    dg: 0,
    cd: 0,
    djia: 0,
    lalian: "",
    xizui: "",
    qifa: "",
    fapiao: "1",
    ke: "",
    tesu: "",
    fuhe: "",
    yinshua: "",
    daixing: "",
    kaiji: "",
  };
  
  // 重置材料数据
  materials.value = materials.value.map(() => ({
    name: "", thickness: 0, density: 0, pricePerGram: 0, gramPerSquareMeter: 0, pricePerSquareMeter: 0
  }));
  
  // 重置工艺参数
  zhidaiPrice.value = 0;
  laPrice.value = 0;
  yinPrice.value = 0;
  fuhePrice.value = 0;
  kaijiPrice.value = 0;
  tejai.value = 0;
  xiPrice.value = 0;
  qiPrcie.value = 0;
  TotalPrice.value = 0;
  
  // 重置丝网烫金表单
  selectedValues.value = {
    quantity: null,
    printArea: null,
    logoColor: null,
    printSides: null,
  };
  matc.value = {
    daidan: 0,
    yun: 0,
    zong: 0,
    fu: 0,
  };
  matchedData.value = null;
};

const Close = () => {
  dictForm.value = {
    dict: "",
    size: "",
    houdu: "",
    price: "",
    num: "",
    resPrice: 0,
    thickness: "",
    jg: 0,
    unit: 0,
  };
  TotalPrice1.value = 0;
};

// 数据初始化
const GetPage = async () => {
  try {
    const tps = await dictList();
    const treeDatas = tps.data.data || [];
    
    // 初始化字典数据
    treeDatas.forEach((item: any) => {
      switch (item.code) {
        case "DX": daixing.value = item.dictDataList; break;
        case "LL": lalian.value = item.dictDataList; break;
        case "QF": qifa.value = item.dictDataList; break;
        case "XZ": qizui.value = item.dictDataList; break;
        case "FH": fuhe.value = item.dictDataList; break;
        case "TSGY": tesugongyi.value = item.dictDataList; break;
        case "KJF": kaijifei.value = item.dictDataList; break;
        case "YS": yinshua.value = item.dictDataList; break;
        case "KP": fapiao.value = item.dictDataList; break;
      }
    });
    
    // 初始化材料数据
    const res = await list();
    tableData.value = res.data || [];
    
    // 初始化可降解材料
    tableDataJIANG.value = [
      { materialName: "无", value: "" },
      ...(tableData.value.filter((item: any) => 
        item.materialName.includes("降解") || item.materialName.includes("可回收"))
      )
    ];
    
    // 初始化数码印刷产品数据
    const productData = await productprices({ pageNo: 1, pageSize: 1000 });
    productDataList.value = productData.data.data || [];
    
    // 初始化烫金数据
    const si = await bronzingList();
    listData.value = (si.data || []).map((item: any) => ({
      quantity: item.orderQuantity,
      printArea: item.printArea,
      logoColor: item.logoColor,
      printSides: item.printSides,
      totalPrice: item.totalPrice,
      unitPrice: item.unitPrice,
    }));
    
    // 初始化系数数据
    const dd = await factorList({});
    factorData.value = dd.data || [];
  } catch (error) {
    console.error("数据初始化失败:", error);
    ElMessage.error("数据加载失败，请刷新页面重试");
  }
};



// 通用工具函数和其他变量定义保持不变
// ...

// 核心计算函数（修改后添加步骤记录）

const userInfo = ref({})
onMounted(() => {
  GetPage();
  userInfo.value = JSON.parse(localStorage.getItem('userInfo'))
});
</script>

<style scoped lang="scss">
.ipt {
  border: 1px solid #cec7c7;
  border-radius: 8px;
  padding: 25px;
  text-align: right;
  font-size: 25px;
  margin: 35px 0;
}
.btn {
  margin: 45px auto;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 20px;
}
.fix {
  display: flex;
  align-items: center;
}

// 新增计算公式区域样式
.calculation-formula {
  margin-top: 30px;
  margin-bottom: 50px;
}

.formula-steps {
  padding-left: 0;
  list-style: none;
}

.formula-steps li {
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px dashed #eee;
  display: flex;
  align-items: flex-start;
}

.step-number {
  font-weight: bold;
  color: #7052ff;
  margin-right: 10px;
  min-width: 24px;
  text-align: right;
}

.step-content {
  flex: 1;
  color: #333;
}

.step-result {
  color: #f56c6c;
  font-weight: 500;
  margin-left: 10px;
  white-space: nowrap;
}
</style>